<!doctype html>
<html lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
 <title>元素拖拽-小懒猫</title>
 <meta name="keywords" content="关键字,关键字"/>
 <meta name="description" content="描述信息">
 <link rel="stylesheet" href="css/common.css" />
  <style>
	#box{position:absolute;top:0;left:0;width:100px;height:100px;background:red;}
  </style>
 </head>
 <body>
	
	<div id="box"></div>

	<script>
		
		function dom(id){
			return document.getElementById(id);
		};

		window.onload = function(){
			//元素拖拽三要素：
			//1:加定位 position:absolute/fixed; 改变的元素:left 和top
			//2:绑定事件:onmousedown (onmousemove onmouseup)---document
			//3:清空鼠标事件
			var boxDom = dom("box");
			boxDom.onmousedown = function(e){
				var movePos = getXY(e);
				document.onmousemove = function(e){
					//移动鼠标的位置
					var movePos = getXY(e);
					var moveLeft = movePos.x;
					var moveTop = movePos.y;
					boxDom.style.left = moveLeft + "px";
					boxDom.style.top = moveTop + "px";
				};
				
				//鼠标松开的时候，释放拖动
				document.onmouseup = function(){
					this.onmousemove = null;
					this.onmouseup = null;
				};
			};
		};
		
		//获取鼠标的位置。兼容ie678
		function getXY(e){
			var ev = e || window.event;
			var x=0,y=0;
			if(ev.pageX){
				x = ev.pageX;
				y = ev.pageY;
			}else{
				//拿到scrollTop 和scrollLeft
				var sleft = 0,stop = 0;
				//ie678---
				if(document.documentElement){
					stop =document.documentElement.scrollTop;
					sleft = document.documentElement.scrollLeft;
				}else{
				//ie9+ 谷歌 
					stop = document.body.scrollTop;
					sleft = document.body.scrollLeft;
				}	
				x = ev.clientX + sleft;
				y = ev.clientY + stop;
			}
			return {x:x,y:y};
		};
	</script>
 </body>
</html>